// ignore_for_file: unnecessary_new, use_build_context_synchronously, prefer_interpolation_to_compose_strings, avoid_print

import 'dart:convert';

import 'dart:io';

import 'dart:ui' as ui;

import 'package:dio/dio.dart';
import 'package:customer_log_app/global/console.dart';
import 'package:file_picker/file_picker.dart';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'dart:math' as math;

import 'package:flutter_toastr/flutter_toastr.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';

class Global {
  // static late Global _instance;
  Dio dio = Dio();

  static Map user = {
    'id': 6,
    'avatar':
        'https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIA7sUz2causwTndCfcTXNO5ObGh5cVuNOFv9t62gvfz07Cc6zAv4dlP6UHXib9n2weKfFP1RV5VFQ/132',
    'name': 'Mr.r',
    'user_type': 'ئالاھىدە ئەزا',
  };
  static String baseUrl = "https://layhe.cn/";
  static String fontUrl =
      "https://elan-1310487162.cos.ap-chengdu.myqcloud.com/";

  static Color appBarColor = rgbToColor('#ff9b00');

  static String baseFont = 'UKIJ Tuz Tom';

  static String lang = 'ug';

  static String channleId = 'elan_channle';
  static String channleName = 'elan_channle_name';
  static String channleDescription = 'elan_channle_description';

  static Color appNavBarColor = rgbToColor('#ff9b00');

  static double appHeight = 650;

  static double appWidth = 1000;

  static Color rgbToColor(String hexString) {
    if (hexString.isEmpty) {
      return Colors.transparent;
    }
    final buffer = StringBuffer();
    if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
    // buffer.write(hexString.replaceFirst('#', ''));
    buffer.write(hexString.replaceAll('#', ''));
    try {
      return Color(int.parse(buffer.toString(), radix: 16));
    } catch (e) {
      // log('color exception:'+e.toString());
      log('color exception:color->$hexString');
      return Colors.black;
    }
  }

  static Future<void> showNotification(
      String title, String body, String content) async {
    final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
        FlutterLocalNotificationsPlugin();
    AndroidNotificationDetails androidPlatformChannelSpecifics =
        AndroidNotificationDetails(channleId, channleName,
            channelDescription: channleDescription,
            importance: Importance.max,
            priority: Priority.high,
            ticker: 'ticker');
    NotificationDetails platformChannelSpecifics =
        NotificationDetails(android: androidPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin
        .show(0, title, body, platformChannelSpecifics, payload: content);
  }

  static void loadTransFile() async {
    var jsonFile = 'assets/trans.json';
    try {
      dynamic langJson = await rootBundle.loadString(jsonFile);
      try {
        dynamic jsonObject = jsonDecode(langJson);
        if (jsonObject[lang] != null) {
          translations = jsonObject[lang];
        }
        transLoaded = true;
      } catch (e) {
        print(e);
      }
    } catch (e) {
      print(e);
    }
  }

  static void loadHomePageMenus() async {
    var jsonFile = 'assets/menus.json';
    try {
      dynamic langJson = await rootBundle.loadString(jsonFile);
      try {
        dynamic jsonObject = jsonDecode(langJson);
        if (jsonObject[lang] != null) {
          menus = jsonObject[lang];
        }
        transLoaded = true;
      } catch (e) {
        print(e);
      }
    } catch (e) {
      print(e);
    }
  }

  static dynamic translations = {};
  static dynamic menus = {};
  static bool transLoaded = false;

  static String trans(String page, String key) {
    if (!transLoaded) {
      loadTransFile();
    }
    if (translations[page] != null) {
      if (translations[page]![key] != null) {
        return translations[page]![key].toString();
      } else {
        print("未经过翻译的字段 $page : $key ");
      }
    } else {
      print("未经过翻译的字段 $page : $key ");
    }

    return page + key;
  }

  static void showToast(BuildContext context, String msg,
      {int? duration, int? position}) {
    try {
      FlutterToastr.show(msg, context, duration: duration, position: position);
    } catch (e) {
      log('toast error');
    }
  }

// 弹出对话框
  static Future<bool?> backPage(BuildContext context) async {
    return showDialog<bool>(
        context: context,
        barrierColor: Colors.transparent,
        builder: (context) {
          return AlertDialog(
            title: Text(
              'ئەسكەرتىش',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 14.0,
                fontFamily: baseFont,
                color: Colors.white,
              ),
            ),
            titlePadding: const EdgeInsets.all(10),
            titleTextStyle: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Colors.blue,
            ),
            content: Text(
              'راستىنلا چېكىنەمسىز؟',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 14.0,
                fontFamily: baseFont,
                color: Colors.white,
              ),
            ),
            contentTextStyle: const TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.normal,
              color: Colors.black,
            ),
            actions: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  GestureDetector(
                    child: Container(
                      width: 100,
                      height: 40,
                      alignment: Alignment.center,
                      decoration: ShapeDecoration(
                        color: Colors.brown,
                        shape: RoundedRectangleBorder(
                          side: const BorderSide(color: Colors.black),
                          borderRadius: BorderRadiusDirectional.circular(5),
                        ),
                      ),
                      child: Text(
                        'ياق',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontFamily: baseFont,
                          fontSize: 14.0,
                          color: Colors.white,
                        ),
                      ),
                    ),
                    onTap: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  GestureDetector(
                    child: Container(
                      width: 100,
                      height: 40,
                      alignment: Alignment.center,
                      decoration: ShapeDecoration(
                        color: Colors.brown,
                        shape: RoundedRectangleBorder(
                          side: const BorderSide(color: Colors.black),
                          borderRadius: BorderRadiusDirectional.circular(5),
                        ),
                      ),
                      child: Text(
                        'ھەئە',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontFamily: baseFont,
                          fontSize: 14.0,
                          color: Colors.white,
                        ),
                      ),
                    ),
                    onTap: () {
                      Navigator.of(context).pop();
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              ),
            ],
            actionsPadding: const EdgeInsets.all(10),
            actionsOverflowButtonSpacing: 10,
            backgroundColor: Colors.black,
            elevation: 10,
            clipBehavior: Clip.antiAlias,
            shape: RoundedRectangleBorder(
              side: const BorderSide(color: Colors.white),
              borderRadius: BorderRadius.circular(5),
            ),
          );
        });
  }

  static void showLoading(BuildContext context, {String text = 'سەل ساقلاڭ'}) {
    try {
      Future.delayed(Duration.zero, () {
        Navigator.push(
          context,
          DialogRouter(
            LoadingDialog3(
              text: text,
            ),
          ),
        );
      });
    } catch (e) {
      log('showLoading error');
    }
  }

  static void hideLoading(BuildContext context) {
    try {
      Future.delayed(Duration.zero, () {
        Navigator.pop(
          context,
          DialogRouter(
            const LoadingDialog3(
              text: 'loading',
            ),
          ),
        );
      });
    } catch (e) {
      log('hideLoading error');
    }
  }

  static Future<void> readFont(String path, String fontFamily) async {
    log('fontFamily:$fontFamily,url:$path');
    var fontLoader = FontLoader(fontFamily);
    fontLoader.addFont(getCustomFont(path));
    await fontLoader.load();
  }

  static Future<ByteData> getCustomFont(String path) async {
    ByteData byteData = await rootBundle.load(path);
    return byteData;
  }

  ///弧度是角的度量单位 单位缩写是rad  360°角=2π弧度
  ///在Flutter中，π 使用 [pi] 来表示 1弧度约为57.3°，1°为π/180弧度
  ///弧度换算成角度 参数[radian]为弧度
  static double radianToAngle(double radian) {
    return radian * 180 / (math.pi);
  }

  ///角度换算成弧度 参数[angle]为角度
  static double angleToRadian(double angle) {
    return angle * math.pi / 180;
  }

  Global() {
    dio.options = BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: const Duration(seconds: 100000),
      sendTimeout: const Duration(seconds: 9999999),
      receiveTimeout: const Duration(seconds: 999990),
      // headers: {
      //   "source": "app",
      // },
      contentType: Headers.formUrlEncodedContentType,
      responseType: ResponseType.json,
    );
    // dio.interceptors.add(InterceptorsWrapper(
    //   onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
    //     log("request:" + options.toString());
    //   },
    //   onResponse: (Response rs, ResponseInterceptorHandler handler) {
    //     log("response:" + rs.toString());
    //   },
    //   onError: (DioError error, ErrorInterceptorHandler handler) {
    //     log("err:" + error.toString());
    //   },
    // ));
  }

  static Future<void> showText(BuildContext context, String text) async {
    await showDialog<int>(
        context: context,
        builder: (BuildContext context) {
          return SimpleDialog(
            title: const Text('خەت مەزمۇنى'),
            children: <Widget>[
              GestureDetector(
                onTap: () {
                  Navigator.pop(context, 1);
                },
                child: Text(text),
              )

              // SimpleDialogOption(
              //   onPressed: () {
              //     // 返回1
              //     Navigator.pop(context, 1);
              //   },
              //   child: const Padding(
              //     padding: EdgeInsets.symmetric(vertical: 6),
              //     child: Text('中文简体'),
              //   ),
              // ),
              // SimpleDialogOption(
              //   onPressed: () {
              //     // 返回2
              //     Navigator.pop(context, 2);
              //   },
              //   child: const Padding(
              //     padding: EdgeInsets.symmetric(vertical: 6),
              //     child: Text('美国英语'),
              //   ),
              // ),
            ],
          );
        });
  }

  static Future<void> showImage(BuildContext context, String url) async {
    await showDialog<int>(
        context: context,
        builder: (BuildContext context) {
          return SimpleDialog(
            title: const Text('رەسىم مەزمۇنى'),
            children: <Widget>[
              GestureDetector(
                onTap: () {
                  Navigator.pop(context, 1);
                },
                child: getContentImage(url),
              )
            ],
          );
        });
  }

  static Widget getContentImage(url) {
    try {
      if (url.toString().contains('data:image')) {
        return Image.memory(
          const Base64Decoder().convert(url.split(',')[1]),
          fit: BoxFit.cover,
        );
      }
      if (url.toString().contains('/data/')) {
        return Image.file(
          File(url),
          fit: BoxFit.cover,
        );
      }
      return Image.network(
        url,
        fit: BoxFit.cover,
      );
    } catch (e) {
      // log(e.toString());
      log('enter catch exception start:' + url);
      var defaultUrl = '${Global.baseUrl}mini/images/fontStyle.png';
      return Image.network(
        defaultUrl,
        fit: BoxFit.cover,
      );
    }
  }

  /// 默认为下载网络图片，如需下载资源图片，需要指定 [isAsset] 为 `true`。
  static Future<void> saveImage(
      BuildContext context, Uint8List imageBytes, String resultImg) async {
    try {
      try {
        if (Platform.isAndroid || Platform.isFuchsia || Platform.isIOS) {
          /// 权限检测
          // PermissionStatus storageStatus = await Permission.storage.status;
          // if (storageStatus != PermissionStatus.granted) {
          //   storageStatus = await Permission.storage.request();
          //   if (storageStatus != PermissionStatus.granted) {
          //     showToast(context, '无法存储图片，请先授权！',
          //         duration: FlutterToastr.lengthShort);
          //     throw '无法存储图片，请先授权！';
          //   }
          // }
          try {
            // PermissionHandler
          } catch (e1) {
            log(e1);
          }
          final result = await ImageGallerySaver.saveImage(imageBytes);

          if (result == null || result == '') {
            showToast(context, trans('camera_one', 'download_failed'),
                duration: FlutterToastr.lengthShort);
          }
        }
        if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
          log('pc img:' + resultImg);
        }
      } catch (e1) {
        log(e1);
      }

      try {
        showToast(context, trans('camera_one', 'download_complete'),
            duration: FlutterToastr.lengthShort);
      } catch (e) {
        log('toast error');
        log(e);
      }
      log("保存成功");
    } catch (e) {
      log(e.toString());
    }
  }

  static Future<void> showLoadingDialog(BuildContext context) {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return Material(
            ///背景透明
            color: const Color.fromARGB(0, 76, 33, 33),

            ///保证控件居中效果
            child: Center(
              ///弹框大小
              child: SizedBox(
                width: 120.0,
                height: 120.0,
                child: Container(
                  ///弹框背景和圆角
                  decoration: const ShapeDecoration(
                    color: Color(0xffffffff),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(
                        Radius.circular(8.0),
                      ),
                    ),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      const CircularProgressIndicator(),
                      Padding(
                        padding: const EdgeInsets.only(
                          top: 20.0,
                        ),
                        child: Text(
                          "加载中",
                          style: TextStyle(
                            fontSize: 18,
                            color: Colors.white,
                            fontFamily: baseFont,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          );
        });
  }

  static dateFormat(DateTime d, String? seperateLabel, String? minuteLabel) {
    seperateLabel = seperateLabel ?? '-';
    minuteLabel = minuteLabel ?? ':';
    String str = '';
    int m = d.month;
    int dy = d.day;
    int h = d.hour;
    int minute = d.minute;
    int second = d.second;
    String month = m.toString();
    String date = dy.toString();
    String hour = h.toString();
    String minuteStr = minute.toString();
    String secondStr = second.toString();
    if (m < 10) {
      month = '0' + month;
    }
    if (dy < 10) {
      date = '0' + date;
    }
    if (h < 10) {
      hour = '0' + hour;
    }
    if (minute < 10) {
      minuteStr = '0' + minute.toString();
    }
    if (second < 10) {
      secondStr = '0' + second.toString();
    }
    str =
        '${d.year}-$month-$date$seperateLabel$hour$minuteLabel$minuteStr$minuteLabel$secondStr';
    return str;
  }

  fileUplod(String localImagePath, String fileName,
      Map<String, dynamic> params) async {
    ///手机中的图片

    ///上传的服务器地址
    String netUploadUrl = "${baseUrl}app/user/upload";

    ///dio 实现文件上传

    ///创建Dio

    params["file"] =
        await MultipartFile.fromFile(localImagePath, filename: fileName);

    ///通过FormData
    FormData formData = FormData.fromMap(params);

    ///发送post
    Response response = await dio.post(
      netUploadUrl, data: formData,

      ///这里是发送请求回调函数
      ///[progress] 当前的进度
      ///[total] 总进度
      onSendProgress: (int progress, int total) {
        log("当前进度是 $progress 总进度是 $total");
      },
    );

    ///服务器响应结果
    var data = response.data;
    log(data);
    return data;
  }

  //方法1：获取网络图片 返回ui.Image
  static Future<ui.Image> getNetImage(String url, {width, height}) async {
    ByteData data = await NetworkAssetBundle(Uri.parse(url)).load(url);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(),
        targetWidth: width, targetHeight: height);
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }

  static saveImageFile(BuildContext context, String imgPath) async {
    var images = await getNetImage(imgPath);
    var pngImageBytes = await images.toByteData(format: ui.ImageByteFormat.png);
    var pngBytes = pngImageBytes!.buffer.asUint8List();

    var android = Platform.isAndroid || Platform.isFuchsia || Platform.isIOS;
    if (android) {
      // 权限检测
      PermissionHandlerPlatform ph = PermissionHandlerPlatform.instance;
      var sorageDenied =
          await ph.checkPermissionStatus(Permission.storage).isDenied;
      if (sorageDenied) {
        List<Permission> permissions = [Permission.storage];
        ph.requestPermissions(permissions);
        sorageDenied =
            await ph.checkPermissionStatus(Permission.storage).isDenied;
        if (sorageDenied) {
          showToast(context, '无法存储图片，请先授权！',
              duration: FlutterToastr.lengthShort);
        }
      }
      Global.saveImage(context, pngBytes, imgPath);
    }
    var win = Platform.isLinux || Platform.isMacOS || Platform.isWindows;
    if (win) {
      try {
        var ext = imgPath.substring(imgPath.lastIndexOf('.'));
        String newFileName = Global.dateFormat(DateTime.now(), '-', '-') + ext;

        var fileNameOne = await FilePicker.platform.saveFile(
            dialogTitle: 'Please select an output file:',
            fileName: newFileName,
            type: FileType.image);
        log(fileNameOne);

        String newImgFile = fileNameOne.toString();

        var f = File(newImgFile);
        var b = await f.exists();

        if (!b) {
          // Should happen only the first time you launch your application
          log("Creating new copy from asset");
          log(newImgFile);
          // Write and flush the bytes written
          try {
            await File(newImgFile).create(recursive: true);
          } catch (_) {}
          await File(newImgFile).writeAsBytes(pngBytes, flush: true);
        }
      } catch (e2) {
        log(e2);
      }
    }
  }
}

class LoadingDialog extends Dialog {
  const LoadingDialog({super.key});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Material(
        ///背景透明
        color: const Color.fromARGB(0, 76, 33, 33),

        ///保证控件居中效果
        child: Center(
          ///弹框大小
          child: SizedBox(
            width: 120.0,
            height: 120.0,
            child: Container(
              ///弹框背景和圆角
              decoration: const ShapeDecoration(
                color: Color(0xffffffff),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(
                    Radius.circular(8.0),
                  ),
                ),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  const CircularProgressIndicator(),
                  Padding(
                    padding: const EdgeInsets.only(
                      top: 20.0,
                    ),
                    child: Text(
                      "加载中",
                      style: TextStyle(
                        fontSize: 18,
                        color: Colors.white,
                        fontFamily: Global.baseFont,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class DialogRouter extends PageRouteBuilder {
  final Widget page;

  DialogRouter(this.page)
      : super(
          opaque: false,
          barrierColor: Colors.transparent,
          pageBuilder: (context, animation, secondaryAnimation) => page,
          transitionsBuilder: (context, animation, secondaryAnimation, child) =>
              child,
        );
}

class LoadingDialog3 extends Dialog {
  final String text;

  const LoadingDialog3({super.key, required this.text});

  @override
  Widget build(BuildContext context) {
    return Material(
      //创建透明层
      type: MaterialType.transparency, //透明类型
      child: Center(
        //保证控件居中效果
        child: Container(
          decoration: const ShapeDecoration(
            color: Color.fromARGB(0, 44, 40, 40),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(
                Radius.circular(8.0),
              ),
            ),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              const CircularProgressIndicator(),
              Padding(
                padding: const EdgeInsets.only(
                  top: 10.0,
                ),
                child: Text(
                  text,
                  style: TextStyle(
                    fontSize: 12.0,
                    color: Colors.black,
                    fontFamily: Global.baseFont,
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
